package com.zouzheng.myproject.filter;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @ClassName LogFilter
 * @Description 生成一次请求的日志唯一ID，用于查询一次请求打印的整个流程的日志
 * @Author zou
 * @Date 2019/5/15 15:50
 **/
@Component
@WebFilter(urlPatterns = "/*")
public class LogFilter implements Filter {

    private final String THREAD_LOG_ID = "threadLogId";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        try {
            MDC.put(THREAD_LOG_ID, System.currentTimeMillis() + "" + Thread.currentThread().getId());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            MDC.remove(THREAD_LOG_ID);
        }


    }
}
